package com.hepinghospital.user.ui;

import android.annotation.SuppressLint;
import android.os.Build;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebStorage;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.constant.JDConstant;
import com.rest.response.QueryProtocolResponse;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

/**
 * Description
 * Created by lbj on 2021/10/11 9:32
 */

public class WebViewActivity extends BaseActivity {
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    String url, rulesType, id, fromWhere;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void initViews() {
        WebSettings webSettings = webview.getSettings();
        webSettings.setUseWideViewPort(true);// 设置此属性，可任意比例缩放
        //自适应屏幕
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        //支持缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls( true );
        webSettings.setAppCacheEnabled(true);
        //解决图片加载不出来问题android webview 从Lollipop(5.0)开始webview默认不允许混合模式，https当中不能加载http资源，而开发的
        //时候可能使用的是https的链接，但是链接中的图片可能是http的，所以需要设置开启。
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSettings.setBlockNetworkImage(false);
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    if (webview != null) {
                        progressBar.setVisibility(View.GONE);//加载完网页进度条消失
                    }

                } else {
                    if (webview != null) {
                        progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                        progressBar.setProgress(newProgress);//设置进度值
                    }
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242

                if (url.contains("sina.cn")) {
                    view.loadUrl("http://ask.csdn.net/questions/178242");
                    return true;
                }
                return false;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (request.getUrl().toString().contains("sina.cn")) {
                        view.loadUrl("http://ask.csdn.net/questions/178242");
                        return true;
                    }
                }

                return false;
            }
        });
        LogUtil.e("链接--" + url);
        if ("CheckRecordFragment".equals(fromWhere)) {
            webview.loadUrl(url);
        } else if ("PermissionDialog".equals(fromWhere) || "LoginActivity".equals(fromWhere)) {
            tvTitle.setText("和平国际医院法律声明及隐私权政策");
            queryProtocol();

        }
    }

    @Override
    protected void initData() {
        fromWhere = getIntent().getStringExtra("fromWhere");
        if ("CheckRecordFragment".equals(fromWhere)) {
            id = getIntent().getStringExtra("patientId");
            url = JDConstant.YSG_HOST + "/record?token=" + RestClient.getInstance().token + "&patientId=" + id;
        } else if ("PermissionDialog".equals(fromWhere)) {
            rulesType = getIntent().getStringExtra("rulesType");
        } else if ("LoginActivity".equals(fromWhere)) {
            rulesType = getIntent().getStringExtra("rulesType");
        }
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_webview;
    }

    //设置返回键动作（防止按返回键直接退出程序)
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO 自动生成的方法存根
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webview.canGoBack()) {//当webview不是处于第一页面时，返回上一个页面
                webview.goBack();
                return true;
            } else {//当webview处于第一页面时
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }


    private void queryProtocol() {
        RestProxy.getInstance().queryProtocol(rulesType, new Observer<QueryProtocolResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(QueryProtocolResponse baseResponse) {
                try {
                    if (webview != null && baseResponse.text != null) {
                        webview.loadDataWithBaseURL(null, baseResponse.text, "text/html", "utf-8", null);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onResume() {
        webview.onResume();
        webview.resumeTimers();
        super.onResume();
    }

    @Override
    public void onPause() {
        webview.onPause();
        webview.pauseTimers();
        super.onPause();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (webview != null) {
            // 清理缓存
            webview.stopLoading();
            webview.onPause();
            webview.clearHistory();
            webview.clearCache(true);
            webview.clearFormData();
            webview.clearSslPreferences();
            WebStorage.getInstance().deleteAllData();
            webview.destroyDrawingCache();
            webview.removeAllViews();
            // 最后再去webView.destroy();
            webview.destroy();
            webview = null;

        }
    }

    @OnClick(R.id.btn_back)
    public void onViewClicked() {
        finish();
    }
}
